using AutoMapper;
using BlogSystem.Common.Config;
using BlogSystem.Common.Config.DI.annotation;
using BlogSystem.Data.Entity;
using BlogSystem.Exception;
using BlogSystem.Model.Respones;
using Microsoft.EntityFrameworkCore;

namespace BlogSystem.Data.Repository.RepositoryImpl;


[Ioc("scoped")]
public class RemarkRepository : BaseRepository<Remark>,IRemarkRepository
{
    private readonly DataBaseContext _dbContext;
    
    private readonly IMapper _mapper;

    public RemarkRepository(DataBaseContext databaseContext,IMapper mapper) : base(databaseContext)
    {     
        _mapper = mapper;
        _dbContext = databaseContext;
    }
    
    public async Task<IQueryable<RemarkResponse>> GetAllByPage(string keyWord, int pageIndex, int pageSize)
    {
        var articlesPage = _dbContext.Set<Remark>()
            .Where(a => a.Status == 1 && (a.Content.Contains(keyWord)))
            .OrderBy(b => b.CreateTime)
            .Skip((pageIndex - 1) * pageSize)
            .Take(pageSize)
            .Select(e => _mapper.Map<RemarkResponse>(e));
     
        return articlesPage;
    }
    
    public async Task<bool> DelRemarkById(int id)
    {
        var remark = await _dbContext.Set<Remark>()
            .FirstOrDefaultAsync(a => a.Status == 1 && a.Id == id);

        if (remark==null)
            throw new BusinessException("信息存在，请重新输入");
        else
        {
            remark.Status = 0;
            await _dbContext.SaveChangesAsync();
            return true;
        }
    }

    public async Task<List<Remark>> GetByArticleId(int id)
    {
        var remarks = _dbContext.Set<Remark>().Where(a => a.Status == 1 && a.ArticleId == id).ToList();
        return remarks;
    }
}